import Vue from 'vue';
import App from './App';
import router from './config/router.config';
import store from './config/store.config';
import vueTap from 'v-tap';
import MintUI, {Lazyload} from 'mint-ui';
import 'mint-ui/lib/style.css';
import $ from 'jquery'
import {
  getAuthCodeUrl,
  initUserIdentity,
  getUserIdentity,
  getUserShippingAddressList
} from 'components/api/interface-hhy';
import {getClientType, setSessionStorageItem, getSessionStorageItem} from 'components/api/utils';
import {BUSINESS_TYPE_TS, BUSINESS_TYPE_WS, BUSINESS_TYPE_STATUS_OPEN, getBranchBusinessInfo} from 'components/api/interface-saas';
import {APP_ENV} from 'components/api/index-local';
import fastclick from 'fastclick';
import './components/amap';

Vue.use(MintUI);
Vue.use(vueTap);
fastclick.attach(document.body);
Vue.use(Lazyload);

// 用于处理页面title和关键词等
import MetaInfo from 'vue-meta-info'
Vue.use(MetaInfo)


function _beforeEach (to, next) {
  let userIdentity = getUserIdentity();
  let businessType = userIdentity.businessType;
  switch (businessType) {
    case BUSINESS_TYPE_WS :   // 外送业务，新用户必须先注册
      if (to.path === '/regist') {
        next();
        break;
      }
      getUserShippingAddressList().then(addresses => {
        if (!(addresses instanceof Array) || addresses.length === 0) {
          next({path: '/regist'});
          return;
        }
        next();
      }).catch(err => {
        console.log(err);
        next({path: '/regist'});
      });
      break;
    case BUSINESS_TYPE_TS:  // 堂食业务，判断门店是否开通堂食
      getBranchBusinessInfo().then(data => {
        let index = data.findIndex((item) => {
          return item.businessType === BUSINESS_TYPE_TS && item.status === BUSINESS_TYPE_STATUS_OPEN;
        });
        if (index === -1) {
          next({name: 'error', params: {message: '门店尚未开通扫码点餐业务'}});
          return;
        }
        next();
      }).catch(err => {
        console.log(err);
        next({name: 'error', params: {message: '门店尚未开通扫码点餐业务'}});
      });
      break;
    default:
      next();
  }
}

// 全局导航钩子
router.beforeEach((to, from, next) => {
  if (to.name === 'error') {
    next();
    return;
  }
  if (getUserIdentity()) {
    _beforeEach(to, next);
    return;
  }

  if (APP_ENV === 'server') {
    let clientType = getClientType();
    if (clientType === '') {
      next({name: 'error', params: {message: '请在微信或支付宝内打开页面'}});
      return;
    }

    // 入口1：扫码点餐  org_id=&shop_id=&table_id=
    // 入口2：外卖/预约自取/预约堂食 authId=&businessType=
    // 我的-订单中心 authId=&businessType=MEMBER

    let authCode = to.query.code;
    let params = {
      branchId: to.query.shop_id ? to.query.shop_id : 0,
      tableId: to.query.table_id ? to.query.table_id : 0,
      businessType: to.query.businessType ? to.query.businessType : BUSINESS_TYPE_TS,
      clientType: clientType,
      authId: to.query.authId ? to.query.authId : ''
    };

    if (authCode) {
      let authParams = {
        code: authCode,
        state: to.query.state,
        appid: to.query.appid ? to.query.appid : ''
      };
      initUserIdentity(params, authParams).then(res => {
        _beforeEach(to, next);
      }).catch(err => {
        // alert(JSON.stringify(err));
        console.log(err);
        next({name: 'error', params: {message: '获取会员失败'}});
      });
    } else {
      let authUrl = getAuthCodeUrl(params, window.location.href);
      // alert(authUrl);
      window.location.href = authUrl;
    }
  } else {
    // 好会员信息获取必须在服务器完成，因此临时测试使用 @todo
    let busiType = to.query.businessType ? to.query.businessType : BUSINESS_TYPE_TS;
    setSessionStorageItem('userIdentity', {
      businessType: busiType,
      orgId: 5823,
      uid: 5320,
      authId: 63,
      branchId: 7135,
      tableId: 0,
      userId: 1270191,
      // userId: 1185795,
      showname: 'yangtl测试',
      // mobile: '',
      mobile: '15064050375',
      // mobile: '',
      levelType: 'FANS'
    });
    _beforeEach(to, next);
  }
});
new Vue({
  router,
  store,
  template: '<App/>',
  components: {
    App
  },
  data: {
    eventHub: new Vue()
  },
  render: (h) => h(App)
}).$mount('#app');
